#include "Ogre.h"
#include "Sound.h"
#include "SoundFactory.h"

using namespace Ogre;
using namespace UniverseSound;

Ogre::String SoundFactory::FACTORY_TYPE_NAME = "SoundClip";

const Ogre::String& SoundFactory::getType() const
{
	return FACTORY_TYPE_NAME;
}

Ogre::MovableObject *SoundFactory::createInstanceImpl(const Ogre::String& name, const Ogre::NameValuePairList *params)
{
	Ogre::String fileName;
	bool loop = false;
	bool stream = false;
	bool prebuffer = false;

	if (params != 0)
	{
		NameValuePairList::const_iterator fileNameIterator = params->find("fileName");
		if (fileNameIterator != params->end())
		{
			// Get fontname
			fileName = fileNameIterator->second;
		}

		NameValuePairList::const_iterator loopIterator = params->find("loop");
		if (loopIterator != params->end())
		{
			// Get fontname
			loop = StringUtil::match(loopIterator->second,"true",false);
		}

		NameValuePairList::const_iterator streamIterator = params->find("stream");
		if (streamIterator != params->end())
		{
			// Get fontname
			stream = StringUtil::match(streamIterator->second, "true", false);
		}

		NameValuePairList::const_iterator preBufferIterator = params->find("preBuffer");
		if (preBufferIterator != params->end())
		{
			// Get fontname
			prebuffer = StringUtil::match(preBufferIterator->second, "true", false);
		}
	}

	// when no caption is set
	if (name == StringUtil::BLANK || fileName == StringUtil::BLANK)
	{
		Ogre::LogManager::getSingleton().logMessage("UniverseSound::SoundFactory::createInstanceImpl(...) - 'name' and 'fileName' parameters are required to construct a sound");
	}

	return SoundManager::getSingletonPtr()->createCustomSound(name, fileName, stream, loop, prebuffer );

}

void SoundFactory::destroyInstance(Ogre::MovableObject *obj)
{
	// Destroy the sound
	SoundManager::getSingletonPtr()->_destroySound(static_cast<SoundClip*>(obj));
}